#include "flash_api.h"
#include "flash_board.h"
#include "temporary_file.h"

void DeleteAllTemporaryFile(void)
{
  FlashDeleteTemporaryFile();
}

void ReadTheEigenvalueFileInformation(uint32_t *pFileSizeOut, uint32_t *pFileTokenOut)
{
  TemporaryFileFormat_t TemporaryFileFormat = {0};

  FlashReadTemporaryFile(0, &TemporaryFileFormat, sizeof(TemporaryFileFormat_t));
  if (pFileSizeOut != NULL)
  {
    *pFileSizeOut = TemporaryFileFormat.FileSize;
  }

  if (pFileTokenOut != NULL)
  {
    *pFileTokenOut = TemporaryFileFormat.FileToken;
  }
}

bool WriteToEigenvalueFileInformation(uint32_t FileSize, uint32_t FileToken)
{
  if (FileSize <= TEMPORARY_FILE_DATA_LENGTH)
  {
    TemporaryFileFormat_t TemporaryFileFormat = {0};

    memset(&TemporaryFileFormat, 0, sizeof(TemporaryFileFormat_t));
    TemporaryFileFormat.FileSize = FileSize;
    TemporaryFileFormat.FileToken = FileToken;
    return FlashWriteTemporaryFile(0, &TemporaryFileFormat, sizeof(TemporaryFileFormat_t));
  }

  return false;
}

void ReadTheEigenvalueFile(uint32_t ReadAddress, uint8_t *pDataOut, uint16_t SizeOut)
{
  TemporaryFileFormat_t TemporaryFileFormat = {0};

  if ((pDataOut != NULL) && (SizeOut > 0))
  {
    FlashReadTemporaryFile(0, &TemporaryFileFormat, sizeof(TemporaryFileFormat_t));
    if ((ReadAddress + SizeOut) <= TemporaryFileFormat.FileSize)
    {
      memcpy(pDataOut, &TemporaryFileFormat.DataPacket[ReadAddress], SizeOut);
    }
  }
}

bool WriteToEigenvalueFile(uint32_t WriteAddress, const uint8_t *pDataIn, uint16_t SizeIn)
{
  TemporaryFileFormat_t TemporaryFileFormat = {0};

  if ((pDataIn != NULL) && (SizeIn > 0))
  {
    FlashReadTemporaryFile(0, &TemporaryFileFormat, sizeof(TemporaryFileFormat_t));
    if ((WriteAddress + SizeIn) <= TemporaryFileFormat.FileSize)
    {
      memcpy(&TemporaryFileFormat.DataPacket[WriteAddress], pDataIn, SizeIn);
      return FlashWriteTemporaryFile(0, &TemporaryFileFormat, sizeof(TemporaryFileFormat_t));
    }
  }

  return false;
}
